<template>
  <div class="map-container">
    <div ref="mapChart" class="map-chart"></div>
    <div class="controls">
      <el-button type="primary" @click="refreshMap">
        <i class="el-icon-refresh-right"></i> 刷新地图
      </el-button>
      <el-button type="success" @click="fetchDeviceData">
        <i class="el-icon-plus"></i> 加载设备数据
      </el-button>
      <el-input
          v-model="searchKeyword"
          placeholder="搜索省份或设备状态"
          @keyup.enter="filterDevices"
      >
        <template #prefix>
          <i class="el-icon-search"></i>
        </template>
      </el-input>
    </div>
    <div class="legend">
      <div class="legend-item">
        <span class="legend-dot" style="background-color: #22c55e;"></span>
        <span class="legend-text">进行中</span>
      </div>
      <div class="legend-item">
        <span class="legend-dot" style="background-color: #eab308;"></span>
        <span class="legend-text">已停止</span>
      </div>
      <div class="legend-item">
        <span class="legend-dot" style="background-color: #ef4444;"></span>
        <span class="legend-text">异常</span>
      </div>
    </div>
    <div v-if="errorMessage" class="error-message">
      <i class="el-icon-warning"></i> {{ errorMessage }}
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, reactive } from 'vue';
import * as echarts from 'echarts';
import axios from 'axios';

const mapChart = ref(null);
let myChart = null;
const errorMessage = ref('');
const searchKeyword = ref('');
const deviceList = ref([]);
const provinceStatusMap = ref({});
const scatterData = ref([]);
const cityCoords = ref({});

onMounted(async () => {
  // 1. 加载 cityCoords.json
  const cityCoordsResp = await fetch('/cityCoords.json');
  cityCoords.value = await cityCoordsResp.json();

  // 2. 加载区县级底图
  const response = await axios.get('/100000_full.json');
  echarts.registerMap('china', response.data);
  myChart = echarts.init(mapChart.value);
  fetchDeviceData();
  window.addEventListener('resize', () => myChart.resize());
});
// 省份坐标
const provinceCoords = reactive({
  "北京市": { lng: 116.4075, lat: 39.9040 },
  "天津市": { lng: 117.4219, lat: 39.1482 },
  "上海市": { lng: 121.4737, lat: 31.2304 },
  "重庆市": { lng: 106.5049, lat: 29.5331 },
  "河北省": { lng: 114.5024, lat: 38.0439 },
  "山西省": { lng: 112.5323, lat: 37.8628 },
  "辽宁省": { lng: 123.4318, lat: 41.8067 },
  "吉林省": { lng: 125.3245, lat: 43.8388 },
  "黑龙江省": { lng: 126.6424, lat: 45.7569 },
  "江苏省": { lng: 118.7674, lat: 32.0415 },
  "浙江省": { lng: 120.1535, lat: 30.2874 },
  "安徽省": { lng: 117.2834, lat: 31.8611 },
  "福建省": { lng: 119.3062, lat: 26.0753 },
  "江西省": { lng: 115.8921, lat: 28.6764 },
  "山东省": { lng: 117.0009, lat: 36.6758 },
  "河南省": { lng: 113.6522, lat: 34.7562 },
  "湖北省": { lng: 114.2985, lat: 30.5843 },
  "湖南省": { lng: 113.0823, lat: 28.2128 },
  "广东省": { lng: 113.2644, lat: 23.1291 },
  "海南省": { lng: 110.3503, lat: 20.0146 },
  "四川省": { lng: 104.0657, lat: 30.5722 },
  "贵州省": { lng: 106.7140, lat: 26.5784 },
  "云南省": { lng: 102.7369, lat: 25.0429 },
  "陕西省": { lng: 108.9480, lat: 34.2631 },
  "甘肃省": { lng: 103.7330, lat: 36.0340 },
  "青海省": { lng: 101.7780, lat: 36.6207 },
  "台湾省": { lng: 121.5000, lat: 25.0000 },
  "内蒙古自治区": { lng: 111.6708, lat: 40.8175 },
  "广西壮族自治区": { lng: 108.3200, lat: 22.8240 },
  "西藏自治区": { lng: 91.1147, lat: 29.6442 },
  "宁夏回族自治区": { lng: 106.2708, lat: 38.4717 },
  "新疆维吾尔自治区": { lng: 87.6868, lat: 43.7724 },
  "其他": { lng: 105.0000, lat: 35.0000 }
});

// 状态 -> 颜色映射（可扩展）
const statusColorMap = {
  '进行中': '#22c55e',
  '已停止': '#eab308',
  '异常': '#ef4444',
  '未知': '#3b82f6',
};


const fetchDeviceData = async () => {
  errorMessage.value = '';
  myChart && myChart.showLoading();

  try {
    const response = await axios.get('/api/device/address');
    const deviceStats = response.data.data || [];

    if (!Array.isArray(deviceStats)) {
      throw new Error('后端返回数据格式错误，期望数组');
    }

    const tempScatterData = [];
    const deviceSet = new Set(); // 用于去重
    deviceStats.forEach(stat => {
      stat.devices.forEach(device => {
        // 设备唯一标识（可用 device_name + location，实际可用设备ID更好）
        const uniqueKey = `${device.device_name}__${device.location}`;
        if (deviceSet.has(uniqueKey)) return;
        deviceSet.add(uniqueKey);
        // 优先用市区坐标
        let addressKey = device.location || stat.device_address;
        // 兼容数据库地址格式
        if (cityCoords[addressKey]) {
          // 完全匹配
        } else {
          // 尝试用省市区前缀匹配
          const keys = Object.keys(cityCoords);
          addressKey = keys.find(k => device.location && device.location.startsWith(k)) || stat.device_address;
        }
        const coords = cityCoords.value[addressKey] || provinceCoords[stat.device_address] || provinceCoords['其他'];
        // 让点有轻微偏移，避免重叠
        const offsetLng = coords.lng + (Math.random() - 0.5) * 0.2;
        const offsetLat = coords.lat + (Math.random() - 0.5) * 0.2;
        tempScatterData.push({
          name: stat.device_address,
          value: [offsetLng, offsetLat],
          itemStyle: {
            color: statusColorMap[device.device_status],
            shadowBlur: 15,
            shadowColor: statusColorMap[device.device_status]
          },
          status: device.device_status,
          deviceName: device.device_name,
          deviceLocation: device.location,
        });
      });
    });
    scatterData.value = tempScatterData;
    renderMap(scatterData.value);
  } catch (error) {
    console.error('获取设备数据失败:', error);
    errorMessage.value = `数据加载失败: ${error.message}`;
    myChart && myChart.setOption({ series: [] });
  } finally {
    myChart && myChart.hideLoading();
  }
};
onMounted(async () => {
  try {
    const response = await axios.get('/china.json');
    echarts.registerMap('china', response.data);
    myChart = echarts.init(mapChart.value);
    fetchDeviceData();
    window.addEventListener('resize', () => myChart.resize());
  } catch (error) {
    console.error('地图初始化失败:', error);
    errorMessage.value = `地图加载失败: ${error.message}`;
  }
});

onUnmounted(() => {
  if (myChart) myChart.dispose();
  window.removeEventListener('resize', () => myChart.resize());
});

const renderMap = (scatterData) => {
  try {
    const option = {
      backgroundColor: 'rgba(15, 23, 42, 0.95)',
      title: { text: '全国设备地理位置分布', left: 'center', textStyle: { color: '#e2e8f0' } },
      tooltip: {
        trigger: 'item',
        backgroundColor: 'rgba(15, 23, 42, 0.85)',
        borderColor: 'rgba(54, 207, 251, 0.5)',
        borderWidth: 1,
        textStyle: { color: '#E2E8F0' },
        formatter: (params) => {
          if (params.seriesType === 'scatter') {
            const province = params.name;
            const provinceDevices = scatterData.filter(
                item => item.name === province
            );

            // 按状态分组统计
            const statusGroups = {};
            provinceDevices.forEach(device => {
              if (!statusGroups[device.status]) {
                statusGroups[device.status] = [];
              }
              statusGroups[device.status].push(device);
            });

            // 构建状态统计HTML
            let statusHtml = '';
            Object.entries(statusGroups).forEach(([status, devices]) => {
              statusHtml += `
                <div style="color:#94A3B8">
                  ${status}: <span style="color:${statusColorMap[status]}">${devices.length}</span>台
                </div>
              `;
            });

            // 构建设备列表HTML（取前3个）
            let deviceListHtml = '';
            provinceDevices.slice(0, 3).forEach(device => {
              deviceListHtml += `
                <div style="margin-top:4px; color:#94A3B8">
                  ${device.deviceName}: ${device.deviceLocation}
                </div>
              `;
            });

            if (provinceDevices.length > 3) {
              deviceListHtml += `<div style="color:#94A3B8">...等${provinceDevices.length}台设备</div>`;
            }

            return `
              <div style="font-weight:bold; color:#36CFFB">${province}</div>
              <div style="color:#94A3B8">总设备数: ${provinceDevices.length}</div>
              ${statusHtml}
              ${provinceDevices.length > 0 ? `
                <div style="margin-top:8px; color:#94A3B8">设备列表:</div>
                ${deviceListHtml}
              ` : ''}
            `;
          }
          return params.name;
        }
      },
      geo: {
        map: 'china',
        roam: true,
        zoom: 3,
        label: {
          show: true,
          color: '#fff',
          fontSize: 12,
          formatter: function(params) {
            // params.name 是区县名
            // params.data && params.data.properties 可能有更详细信息
            if (params.data && params.data.properties) {
              // 优先显示全名
              return params.data.properties.name || params.name;
            }
            return params.name;
          }
        },
        itemStyle: {
          areaColor: 'rgba(30, 41, 59, 0.5)',
          borderColor: '#36CFFB',
          borderWidth: 2
        },
        emphasis: {
          label: {
            show: true,
            color: '#FFD700',
            fontWeight: 'bold'
          },
          itemStyle: {
            areaColor: 'rgba(54, 207, 251, 0.1)'
          }
        }
      },
      series: [
        {
          name: '设备分布',
          type: 'scatter',
          coordinateSystem: 'geo',
          data: scatterData,
          symbolSize: 10, // 统一大小，或根据设备数量调整
          label: {
            show: false,
            position: 'top',
            color: '#e2e8f0',
            formatter: (params) => {
              const province = params.name;
              const count = scatterData.filter(
                  item => item.name === province
              ).length;
              return `${province}\n${count}`;
            }
          },
          emphasis: {
            label: {
              show: true
            }
          }
        }
      ]
    };

    myChart.setOption(option);
  } catch (error) {
    console.error('渲染地图失败:', error);
    errorMessage.value = `地图渲染失败: ${error.message}`;
  }
};

// 根据设备状态获取颜色
const getDeviceColor = (status) => {
  switch (status) {
    case '进行中': return '#22c55e';
    case '已停止': return '#eab308';
    case '异常': return '#ef4444';
    default: return '#3b82f6';
  }
};

// 刷新地图
const refreshMap = () => {
  fetchDeviceData();
};

const filterDevices = () => {
  if (!searchKeyword.value.trim()) {
    renderMap(scatterData.value);
    return;
  }
  const keyword = searchKeyword.value.toLowerCase();
  const filteredData = scatterData.value.filter(item =>
      item.name.toLowerCase().includes(keyword) ||
      item.status.toLowerCase().includes(keyword)
  );
  renderMap(filteredData);
};
</script>

<style scoped>
/* 保持原有样式不变 */
.map-container {
  width: 100%;
  height: 600px;
  position: relative;
  background: linear-gradient(135deg, #0F172A 0%, #1E293B 100%);
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.3);
  font-family: 'Inter', system-ui, sans-serif;
}

.map-chart {
  width: 100%;
  height: 100%;
}

.controls {
  position: absolute;
  bottom: 24px;
  left: 24px;
  z-index: 10;
  display: flex;
  gap: 16px;
  align-items: center;
}

.controls .el-button {
  padding: 10px 16px;
  border-radius: 8px;
  font-weight: 500;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 8px;
  background: rgba(54, 207, 251, 0.1);
  border: 1px solid rgba(54, 207, 251, 0.3);
  color: #FFFFFF;
}

.controls .el-button:hover {
  background: rgba(54, 207, 251, 0.2);
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(54, 207, 251, 0.2);
}

.controls .el-button--primary {
  background: rgba(54, 207, 251, 0.8);
  border-color: rgba(54, 207, 251, 0.5);
}

.controls .el-button--primary:hover {
  background: rgba(54, 207, 251, 1);
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(54, 207, 251, 0.3);
}

.controls .el-button--success {
  background: rgba(54, 211, 153, 0.8);
  border-color: rgba(54, 211, 153, 0.5);
}

.controls .el-button--success:hover {
  background: rgba(54, 211, 153, 1);
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(54, 211, 153, 0.3);
}

.controls .el-input {
  width: 240px;
}

.controls .el-input__wrapper {
  background: rgba(30, 41, 59, 0.8);
  border: 1px solid rgba(54, 207, 251, 0.3);
  border-radius: 8px;
  color: #E2E8F0;
  box-shadow: none;
  transition: all 0.3s ease;
}

.controls .el-input__prefix {
  color: #94A3B8;
}

.controls .el-input__wrapper:focus,
.controls .el-input__wrapper:hover {
  background: rgba(30, 41, 59, 1);
  border-color: rgba(54, 207, 251, 0.5);
}

.legend {
  position: absolute;
  bottom: 24px;
  right: 24px;
  z-index: 10;
  display: flex;
  gap: 16px;
  background: rgba(15, 23, 42, 0.7);
  padding: 10px 16px;
  border-radius: 8px;
  backdrop-filter: blur(4px);
  border: 1px solid rgba(54, 207, 251, 0.2);
}

.legend-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.legend-dot {
  width: 12px;
  height: 12px;
  border-radius: 50%;
  display: inline-block;
}

.legend-text {
  color: #E2E8F0;
  font-size: 12px;
}

.error-message {
  position: absolute;
  top: 100px;
  left: 50%;
  transform: translateX(-50%);
  background: rgba(248, 114, 114, 0.9);
  color: #FFFFFF;
  padding: 12px 24px;
  border-radius: 8px;
  z-index: 20;
  display: flex;
  align-items: center;
  gap: 8px;
  box-shadow: 0 10px 20px rgba(248, 114, 114, 0.2);
  opacity: 0;
  animation: fadeIn 0.5s ease forwards;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translate(-50%, -20px);
  }
  to {
    opacity: 1;
    transform: translate(-50%, 0);
  }
}
</style>